package com.czy.daishusys.ui.message;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.czy.daishusys.R;
import com.czy.daishusys.adapter.MailListAdapter;
import com.czy.daishusys.db.UserHelper;
import com.czy.daishusys.entity.BaseList;
import com.czy.daishusys.entity.BaseResultEntity;
import com.czy.daishusys.entity.ConstantsModel;
import com.czy.daishusys.entity.ShareContactsBean;
import com.czy.daishusys.global.Constants;
import com.czy.daishusys.ui.BaseFragment;
import com.czy.daishusys.utils.ContactsManager;
import com.czy.daishusys.utils.GsonUtils;
import com.czy.daishusys.utils.MyLog;
import com.czy.daishusys.utils.PhoneUtils;
import com.czy.daishusys.widget.common.IndexBar;
import com.google.gson.reflect.TypeToken;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.content.ContentValues.TAG;
import static android.content.Context.INPUT_METHOD_SERVICE;
import static com.czy.daishusys.global.Constants.PAGE_SIZE;


/**
 * Created by hep on 2017/11/24.
 * 门店联系人
 */

public class ContactsFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {


    @BindView(R.id.recyler_view_list)
    RecyclerView recylerViewList;
    Unbinder unbinder;
    @BindView(R.id.share_add_contact_sidebar)
    IndexBar shareAddContactSidebar;
    @BindView(R.id.dialog_letter_hint_textview)
    TextView dialogLetterHintTextview;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.et_search_contacts)
    EditText etSearchContacts;
    @BindView(R.id.img_search_contacts)
    ImageView imgSearchContacts;
    private LinearLayoutManager mLayoutManager;
    private LinkedHashMap<Integer, String> mHeaderList;
    private ArrayList<ShareContactsBean> mContactList;
    private MailListAdapter mAdapter;
    private int mNextRequestPage = 1;
    //当搜索数据为空的时候，视图
    private View emptyView;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_contacts;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        setStatusBar();

    }

    @Override
    protected void updateViews() {
//        fetchData();
        etSearchContacts.setHint(R.string.meassage_menber_hint_text);
        swipeLayout.setOnRefreshListener(this);
        recylerViewList.setLayoutManager(mLayoutManager = new LinearLayoutManager(getActivity()));
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.shape_line_divider_decoration));
        recylerViewList.addItemDecoration(dividerItemDecoration);
        //利用分割线实现悬浮框
//        recylerViewList.addItemDecoration(
//                new FloatingBarItemDecoration(getActivity(), mHeaderList));
        mAdapter = new MailListAdapter(R.layout.item_mail_list_recyler, null);
        recylerViewList.setAdapter(mAdapter);
        emptyView = LayoutInflater.from(getActivity()).inflate(R.layout.empty_message_contacts, (ViewGroup) recylerViewList.getParent(), false);

//        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_call, (ViewGroup) getActivity().getWindow().getDecorView());
//        View view = LayoutInflater.from(getActivity()).inflate(R.layout.header_contacts_search, (ViewGroup) recylerViewList.getParent(), false);
//        etSearchContacts = (EditText) view.findViewById(R.id.et_search_contacts);
//        mAdapter.addHeaderView(view, 0);

//        shareAddContactSidebar.setNavigators(new ArrayList<>(mHeaderList.values()));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ConstantsModel constantsModel = (ConstantsModel) mAdapter.getData().get(position);
                startActivity(new Intent(getActivity(), StoreContactsListActivity.class).putExtra("storeId", constantsModel.getStoreId() + ""));

            }
        });
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        });
        etSearchContacts.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                /*隐藏软键盘*/
                    InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
                    if (inputMethodManager.isActive()) {
                        inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }

//                    if (etSearchContacts.getText().toString().trim() == null || TextUtils.isEmpty(etSearchContacts.getText().toString().trim())) {
//                        mMStatusDialog.show(getResources().getString(R.string.search_empty), getResources().getDrawable(R.drawable.mn_progress_dialog_bg));
//                    } else {
                    onRefresh();
//                    }


                    return true;
                }
                return false;


            }
        });
        etSearchContacts.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (PhoneUtils.isEmpty(etSearchContacts.getText().toString().trim())) {
                    onRefresh();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
//        shareAddContactSidebar.setOnTouchingLetterChangedListener(new IndexBar.OnTouchingLetterChangeListener() {
//            @Override
//            public void onTouchingLetterChanged(String s) {
//                dialogLetterHintTextview.setVisibility(View.VISIBLE);
//                dialogLetterHintTextview.setText(s);
//                for (Integer position : mHeaderList.keySet()) {
//                    if (mHeaderList.get(position).equals(s)) {
//                        mLayoutManager.scrollToPositionWithOffset(position, 0);
//                        return;
//                    }
//                }
//            }
//
//            @Override
//            public void onTouchingStart(String s) {
//                dialogLetterHintTextview.setVisibility(View.VISIBLE);
//                dialogLetterHintTextview.setText(s);
//            }
//
//            @Override
//            public void onTouchingEnd(String s) {
//                dialogLetterHintTextview.setVisibility(View.GONE);
//            }
//        });
        imgSearchContacts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        swipeLayout.setRefreshing(true);
        onRefresh();
    }

    //set数据
    private void setData(boolean isRefresh, List data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
            if (size == 0 && etSearchContacts.getText().toString().trim().length() > 0) {
                mAdapter.setEmptyView(emptyView);
            }
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }

    @Override
    public void onRefresh() {
        mNextRequestPage = 1;
        mAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        postDataContacts(true);
    }

    private void loadMore() {

        postDataContacts(false);
    }

    //获取门店
    public void postDataContacts(final boolean isFrist) {


        HttpParams params = new HttpParams();
        params.put("session", UserHelper.getInstance().getSession(getActivity()));
        params.put("pageSize", PAGE_SIZE + "");
        params.put("pageNumber", mNextRequestPage + "");

        params.put("search", etSearchContacts.getText().toString().trim());
        params.put("pid",UserHelper.getInstance().getDevicePid());
        MyLog.e("hep", "param = " + params.toString());
        EasyHttp.post(Constants.SYS_USER_INFO_STORES)
                .params(params)
                .timeStamp(true)//添加时间戳
                .execute(new CallBack<String>() {
                    @Override
                    public void onStart() {
//                        mMProgressDialog.show();
                    }

                    @Override
                    public void onCompleted() {
//                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onSuccess(String string) {
                        MyLog.e("EasyHttp", string);
                        String data = PhoneUtils.checkResponseFlag(getActivity(), string);
                        if (PhoneUtils.isEmpty(data))
                            return;
//                        BaseResultEntity<List<ConstantsModel>> model = new Gson().fromJson(string, BaseResultEntity.class);
                        BaseResultEntity<BaseList<ConstantsModel>> model = GsonUtils.fromJson(string, new TypeToken<BaseResultEntity<BaseList<ConstantsModel>>>() {
                        }.getType());
                        if (isFrist) {
                            mAdapter.setEnableLoadMore(true);
                            swipeLayout.setRefreshing(false);
                        }
                        if (model.isFlag()) {
                            setData(isFrist, model.getData().getList());
                        } else {
                            setError(isFrist);
//                            mMStatusDialog.show(model.getExp(), getResources().getDrawable(R.drawable.mn_progress_dialog_bg));
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "门店列表 error = " + e.getMessage());
                        setError(isFrist);
//                        mMStatusDialog.show(getResources().getString(R.string.network_error), getResources().getDrawable(R.drawable.mn_progress_dialog_bg));
                    }
                });
//                    @Override
//                    public void onSuccess(BaseResultEntity<List<ConstantsModel>> model) {
////                        MyLog.d(TAG, "门店列表 " + s);
//
//
//
//                    }
//
//                    @Override
//                    public void onError(ApiException e) {
//                        super.onError(e);
//
//                    }
//                });


    }

    public void setError(boolean isFrist) {
        if (isFrist) {
            mAdapter.setEnableLoadMore(true);
            swipeLayout.setRefreshing(false);
        } else {
            mAdapter.loadMoreFail();
        }
    }

    /**
     * fetch the data to display
     * need permission of Manifest.permission.READ_CONTACTS
     */

    //创建头部数据
    private void fetchData() {
        if (mHeaderList == null) {
            mHeaderList = new LinkedHashMap<>();
        }
        fetchContactList();
    }

    protected void fetchContactList() {
        mContactList = ContactsManager.getPhoneContacts(getActivity());

        mHeaderList.clear();
        if (mContactList.size() == 0) {
            return;
        }

        //从1开始是因为adapter加了头部
        addHeaderToList(1, mContactList.get(0).getInitial());
        for (int i = 1; i < mContactList.size(); i++) {
            if (!mContactList.get(i - 1).getInitial().equalsIgnoreCase(mContactList.get(i).getInitial())) {
                addHeaderToList(i + 1, mContactList.get(i).getInitial());
            }
        }


    }

    private void addHeaderToList(int index, String header) {
        mHeaderList.put(index, header);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


}
